package util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBHelper {

    //连接数据库的URL地址
    private static final String url="jdbc:mysql://localhost:3306/readingocean?serverTimezone=Hongkong";
    private static final String driver = "com.mysql.cj.jdbc.Driver";
    private static final String username="root";//数据库的用户名
    private static final String password="123456";//数据库的密码

    private static Connection connection = null;

    //单例模式返回数据库连接对象
    public static Connection getConnection() throws Exception {
        if(connection==null) {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
            return connection;
        }
        return connection;
    }

    public static void main(String[] args) {
        try {
            Connection c = DBHelper.getConnection();
            if(c!=null) {
                System.out.println("数据库连接正常！");
            }
            else {
                System.out.println("数据库连接异常！");
            }
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}
